ts.facetplot <- function(data, variables, index = data){
  dta.tmp <- data.frame(date = as.Date(index(index)),
                        data[,variables]) %>%
    gather(key = variable,value = value,-date)
  
  ggplot(data = dta.tmp,mapping = aes(x = date,y = value,group = variable, colour = variable), facet) +
    geom_smooth(se = FALSE, span = 0.2, colour = "lightgrey", method = "loess") +
    geom_line(size = 1) +
    facet_grid(facets = variable ~.,scales = "free_y") +
    scale_x_date(date_breaks = "1 year",date_labels = "%Y") +
    theme_bw() +
    theme(legend.position="none")
}

irf.normalise <- function(irf){
  tmp.1 <- lapply(irf[c("irf", "Lower", "Upper")], FUN = function(x){
    lapply(x, FUN = function(y){
      z <- gather(as.data.frame(y),key = "response") 
    })
  })
  
  tmp.2 <- lapply(tmp.1, function(x){
    bound <- do.call("rbind",x)
    mutate(bound,impulse = row.names(bound))
  })
  
  tmp.3 <- do.call("rbind",tmp.2)
  tmp.3$type <- rownames(tmp.3)
  
  tmp.3$impulse <- sub("\\..*", "",tmp.3$impulse)
  tmp.3$type <- sub("\\..*", "",tmp.3$type)
  rownames(tmp.3) <- NULL
  
  tmp.3$step <- rep(1:nrow(irf[[1]][[1]]),
                    nrow(tmp.3)/nrow(irf[[1]][[1]]))
  
  impulses <- unique(tmp.3$impulse)
  
  for (imp in impulses) {
    norm.obs <- which(tmp.3$impulse == imp &
                        tmp.3$response == imp & 
                        tmp.3$type == "irf" & 
                        tmp.3$step == 1)
    to.replace <- which(tmp.3$impulse == imp)
    
    tmp.3$value[to.replace] <- tmp.3$value[to.replace] / tmp.3$value[norm.obs]
  }
  
  tmp.3 <- spread(tmp.3, key = "type", value = "value")
  tmp.3 <- tmp.3[,c("step", "impulse", "response", "irf", "Lower", "Upper")] 
  
  return(tmp.3)
}

norm.irf.plot<- function(irf, 
                          imp, imp.label = imp,
                          resp, resp.label = resp, 
                          invert = FALSE){
  data.tmp <- dplyr::filter(irf, impulse == imp, response == resp)
  data.tmp$step <- data.tmp$step-1
  if(invert == TRUE) {
    data.tmp$irf <- -data.tmp$irf
    data.tmp$Lower <- -data.tmp$Lower
    data.tmp$Upper <- -data.tmp$Upper
  }
  
  ggplot(data.tmp,mapping = aes(step,irf, ymin = -1,ymax = 1)) +
    geom_ribbon(mapping = aes(ymin = Lower, ymax = Upper),
                colour = "gray", linetype = "dashed", fill = "gray", alpha = 0.3) +
    geom_line(colour = "black") +
    ggtitle(label = paste("Impulse: ",imp.label, " | Response: ", resp.label)) +
    scale_x_continuous(name = "Months after shock", breaks = seq(0,nrow(data.tmp)-1,1)) +
    scale_y_continuous(name = "Impulse Response") +
    theme_bw() +
    theme(plot.title = element_text(size = 11, face = "bold"),
          panel.grid = element_line(linetype = "dashed")) 
    
}
